<?php

namespace app\api\controller;

use app\common\model\TeamFound;
use app\common\logic\UsersLogic;
use app\common\logic\OrderLogic;
use think\Page;
use think\Request;
use think\db;
use think\Session;
class Order extends ApiCommon{

    public $user_id = 0;
    public $user = array();
	
    public function _initialize()
    {
    	$this->nocheckArr = ['comment_upload','return_goods_upload','custom_upload'];   	
		parent::_initialize();
    }

    /**
     * 订单列表
     * @return mixed
     */
    public function order_list()
    {
    	$user_id = I('uid/d',0);
		$types = I('type');
		$page = I('page/d',0);
		
		$this->user_id = $user_id;
		
        $where = ' user_id=' . $this->user_id;
        //条件搜索
        if($types){
            $where .= C(strtoupper($types));
        }
        $where.=' and order_prom_type < 5 ';//虚拟订单和拼团订单不列出来
        $count = M('order')->where($where)->count();
        
		$pagesiez = C('PAGESIZE');
		$startpage = $page*$pagesiez;
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($startpage. ',' . $pagesiez)->select();

			
        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }
		
		$ostate = 0;
        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = 0;
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
			$ostate = $value['order_status'];
			if (($value['shipping_status'] == 1 && $ostate==1) || $ostate == 4){
				$invoice_no = M('DeliveryDoc')->where("order_id", $value['order_id'])->getField('invoice_no', true);
            	$order_list[$key]['invoice_no'] = implode(' , ', $invoice_no);
			}
        }

		//订单列表
		 $this->returnMsg('ok','',$order_list);
    }
	
	public function order_select(){
		$p = I('p/s','');
		$user_id = I('uid/d');
		
		
	}
	
	/**
     * 订单详情
     * @return mixed
     */
    public function order_detail()
    {
        $id = I('id/d');
		$user_id = I('uid/d');
		
		$this->user_id = $user_id;
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        if (!$order_info) {
			 $this->returnMsg('-1','没有获取到订单信息');
        }
        //获取订单商品
        $model = new UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];
		
		//获取区域列表。觉得完全没有必要
//      $region_list = get_region_list();
        $invoice_no = M('DeliveryDoc')->where("order_id", $id)->getField('invoice_no', true);
        $order_info['invoice_no'] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id' => $id))->select();
		

		
		$backArr = [];
		$backArr['order_info'] = $order_info;
		$backArr['order_action'] = $order_action;	
		$this->returnMsg('ok','',$backArr);
    }

    /**
    * 取消订单
    */
    public function cancel_order()
    {
        $id = I('id/d');
        $uid = I('uid/d');
        $this->user_id = $uid;
        //检查是否有积分，余额支付
        $logic = new OrderLogic();
        $data = $logic->cancel_order($this->user_id, $id);
		exit(json_encode($data));
    }
	

    /**
     * 确定收货成功
     */
    public function order_confirm()
    {
        $id = I('id/d', 0);
		$user_id = I('uid/d', 0);
		$this->user_id = $user_id;
		
		//却收货里面还有下单送礼物的操作
        $data = confirm_order($id, $this->user_id);

        if ($data['status'] != 1) {
			$this->returnMsg('-1',$data['msg']);
        } else {
			$data['status'] = 'ok';
			exit(json_encode($data));
        }
    }
	
    //订单支付后取消订单(这步操作只显示取消订单的操作页面)
    public function refund_order()
    {
        $order_id = I('order_id/d');
		$user_id = I('uid/d');
		$this->user_id = $user_id;
		
        $order = M('order')
            ->field('order_id,pay_code,pay_name,user_money,integral_money,coupon_price,order_amount')
            ->where(['order_id' => $order_id, 'user_id' => $this->user_id])
            ->find();

        $this->returnMsg('ok','',$order);
    }
	
    //申请取消订单
    public function record_refund_order()
    {
    	//订单编号
        $order_id   = input('order_id', 0);
		//退款原因
        $user_note  = input('user_note', '');
		//收货人
        $consignee  = input('consignee', '');
		//手机号码
        $mobile     = input('mobile', '');
		//用户编号
		$user_id 	= input('uid/d',0);
		
		$this->user_id = $user_id;
        $logic = new \app\common\logic\OrderLogic;
        $return = $logic->recordRefundOrder($this->user_id, $order_id, $user_note, $consignee, $mobile);
		
		exit(json_encode($return));
    }

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $rec_id = I('rec_id',0);
		$user_id = I('uid/d');
		$this->user_id = $user_id;
		
        $return_goods = M('return_goods')->where(array('rec_id'=>$rec_id))->find();
        if(!empty($return_goods))
        {
        	$this->returnMsg(-1,'已经提交过退货申请');
        }
        $order_goods = M('order_goods')->where(array('rec_id'=>$rec_id))->find();
        $order = M('order')->where(array('order_id'=>$order_goods['order_id'],'user_id'=>$this->user_id))->find();
        $confirm_time_config = tpCache('shopping.auto_service_date');//后台设置多少天内可申请售后
        $confirm_time = $confirm_time_config * 24 * 60 * 60;
        if ((time() - $order['confirm_time']) > $confirm_time && !empty($order['confirm_time'])) {
			$this->returnMsg(-2,'已经超过' . $confirm_time_config . '天内退货时间');
        }
		
        if(empty($order)){
			$this->returnMsg(-3,'非法操作');
		}
		
        $model = new OrderLogic();
        $res = $model->addReturnGoods($rec_id,$order);  //申请售后
        if($res['status']==1){
//      	$this->success($res['msg'],U('Order/return_goods_list'));
			$this->returnMsg('ok',$res['msg']);
		}
		else{
			exit($res);
		}
    }

    /**
     * 退换货列表
     */
    public function return_goods_list()
    {
    	$user_id = I('uid/d');
		$page = I('page/d',0);
		$this->user_id = $user_id;
		
        //退换货商品信息
        $count = M('return_goods')->where("user_id", $this->user_id)->count();
        $pagesize = C('PAGESIZE');
        $startpage = $page * $pagesize;

//		$list = Db::name('return_goods')->alias('rg')
//          ->field('rg.*,og.goods_name,og.spec_key_name')
//          ->join('order_goods og','rg.rec_id=og.rec_id','LEFT')
//          ->where(['rg.user_id'=>$this->user_id])
//          ->order("rg.id desc")
//          ->limit("$startpage,$pagesize")
//          ->select();
		
		$list = Db::query("select rg.*,og.goods_name,og.spec_key_name,tg.original_img from tp_return_goods as rg,tp_order_goods og,tp_goods as tg
		where rg.rec_id=og.rec_id and rg.goods_id = tg.goods_id and rg.user_id=? order by rg.id desc limit $startpage,$pagesize",[$this->user_id]);
		
		$backArr = [];
		$backArr['list'] = $list;
		$backArr['count'] = $count;
		
		$this->returnMsg('ok','',$backArr);
    }

    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id/d', 0);
		$user_id = I('uid/d');
		$this->user_id = $user_id;
        $return_goods = M('return_goods')->where("id = $id")->find();
        $return_goods['seller_delivery'] = unserialize($return_goods['seller_delivery']);  //订单的物流信息，服务类型为换货会显示
        if ($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();

		$backArr = [];
		$backArr['goods'] = $goods;
		$backArr['return_goods'] = $return_goods;
		
		$this->returnMsg('ok','',$backArr);
    }
	
	//老的分页显示
    public function return_goods_refund()
    {
        $order_sn = I('order_sn');
        $where = array('user_id'=>$this->user_id);
        if($order_sn){
            $where['order_sn'] = $order_sn;
        }
        $where['status'] = 5;
        $count = M('return_goods')->where($where)->count();
        $page = new Page($count,10);
        $list = M('return_goods')->where($where)->order("id desc")->limit($page->firstRow, $page->listRows)->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goodsList = M('goods')->where("goods_id in (".  implode(',',$goods_id_arr).")")->getField('goods_id,goods_name');
        $this->assign('goodsList', $goodsList);
        $state = C('REFUND_STATUS');
        $this->assign('list', $list);
        $this->assign('state',$state);
        $this->assign('page', $page->show());// 赋值分页输出
        return $this->fetch();
    }

    /**
     * 取消售后服务
     * @author lxl
     * @time 2017-4-19
     */
    public function return_goods_cancel(){
        $id = I('id',0);
		$user_id = I('uid/d',0);
		
		$this->user_id = $user_id;
        if(empty($id)){
        	$this->returnMsg('-1','参数错误');
		}
        $return_goods = M('return_goods')->where(array('id'=>$id,'user_id'=>$this->user_id))->find();
        if(empty($return_goods)){
			$this->returnMsg('-1','参数错误');
        } 
		
        M('return_goods')->where(array('id'=>$id))->save(array('status'=>-2,'canceltime'=>time()));
		
		$this->returnMsg('ok','取消成功');
    }
	
	
    /**
     * 换货商品确认收货
     * @author lxl
     * @time  17-4-25
     * */
    public function receiveConfirm(){
        $return_id=I('return_id/d');
		$user_id = I('uid/d',0);
		$this->user_id = $user_id;
		
        $return_info=M('return_goods')->field('order_id,order_sn,goods_id,spec_key')->where('id',$return_id)->find(); //查找退换货商品信息
        $update = M('return_goods')->where('id',$return_id)->save(['status'=>3]);  //要更新状态为已完成
        if($update) {
            M('order_goods')->where(array(
                'order_id' => $return_info['order_id'],
                'goods_id' => $return_info['goods_id'],
                'spec_key' => $return_info['spec_key']))->save(['is_send' => 2]);  //订单商品改为已换货			
			$this->returnMsg('ok','操作成功');
        }
		$this->returnMsg('-1','操作失败');
    }

    /**
     *  评论晒单
     * @return mixed
     */
    public function comment()
    {
    	$user_id = I('uid/d',0);
		$status = I('status/d',2);
		$page = I('page/d',0);
		$oid = I('oid/d',0);
		
		
		$this->user_id = $user_id;       
		$logic = new \app\common\logic\CommentLogic;		
		if($oid>0){
			$result = $logic->getCommentById($user_id,$oid);
		}
		else{
			$result = $logic->getCommentPage($user_id, $status,$page); //获取评论列表
		}
		
        $this->returnMsg('ok','',$result);
    }

    /**
     *添加评论
     */
    public function add_comment()
    {
        if (IS_POST) {
            // 晒图片
//          $files = request()->file('comment_img_file');
//          $save_url = 'public/upload/comment/' . date('Y', time()) . '/' . date('m-d', time());
//          foreach ($files as $file) {
//              // 移动到框架应用根目录/public/uploads/ 目录下
//              $image_upload_limit_size = config('image_upload_limit_size');
//              $info = $file->rule('uniqid')->validate(['size' => $image_upload_limit_size, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
//              if ($info) {
//                  // 成功上传后 获取上传信息
//                  // 输出 jpg
//                  $comment_img[] = '/'.$save_url . '/' . $info->getFilename();
//              } else {
//                  // 上传失败获取错误信息
//                  $this->error($file->getError());
//              }
//          }
//          if (!empty($comment_img)) {
//              $add['img'] = serialize($comment_img);
//          }
			
			$this->user_id = I('uid/d');
            $user_info = session('user');
            $logic = new UsersLogic();
			//商品
            $add['goods_id'] = I('goods_id/d');
			if(!$user_info){
				$add['email'] = '';
			}
			else{
				$add['email'] = $user_info['email'];
			}
            
			//是否匿名
            $hide_username = I('hide_username');
            if (empty($hide_username)) {
            	if(!$user_info){
					$add['username'] = '';
				}
				else{
					$add['username'] = $user_info['nickname'];
				}               
            }
            $add['is_anonymous'] = $hide_username;  //是否匿名评价:0不是\1是
            $add['order_id'] = I('order_id/d');
			//店家服务态度
            $add['service_rank'] = I('service_rank');           
			//物流发货速度
            $add['deliver_rank'] = I('deliver_rank');
			//商品符合度
            $add['goods_rank'] = I('goods_rank');
            $add['is_show'] = 1; //默认显示
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['add_time'] = time();
            $add['ip_address'] = request()->ip();
            $add['user_id'] = $this->user_id;
			$imgstr = I('imgs/s','');
			$imgarr = explode(',', $imgstr);		
			$countimg = count($imgarr);
			
			$add['img'] = '';
			if($imgstr != ''){
				for($i=0;$i<$countimg;$i++){
					$imgarr[$i] = '/'.$imgarr[$i];
				}
				$add['img'] = serialize($imgarr); //I('imgs');
			}

            //添加评论
            $row = $logic->add_comment($add);
            if ($row['status'] == 1) {
				$this->returnMsg('ok','评论成功');
            } else {
				$this->returnMsg(-1,$row['msg']);
            }
        }
    }
	
	
	//退款上传图片
	public function return_goods_upload(){
		$imgtop = 'public/uploads/returngoods/';		
		$this->image_upload($imgtop);
    }
	
	//评论图片
	public function comment_upload(){
		$imgtop = 'public/uploads/comment/';		
		$this->image_upload($imgtop);
	}
	
	//定制上传图片
	public function custom_upload(){
		$imgtop = 'public/uploads/custom/';		
		$this->image_upload($imgtop);
    }
	
	public function image_upload($imgtop){
		ob_end_clean();
        $file = request()->file('file');
		
        $info = $file->move(ROOT_PATH . $imgtop);
        if($info){
            $imageurl = $info->getSaveName();			
			$imageurl = preg_replace('/\\\\/', '/', $imageurl);		
			
			$allurls = $imgtop.$imageurl;
				
            $this->returnMsg('ok','',$allurls);
        }
        else{
            $this->returnMsg('-1',$file->getError());
        }
    }



}